package com.example.testdemo.recyclerview_gallery_load.loadmore;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.testdemo.R;

/**
 * 加载更多adapter
 * Created by zhangwenxiang on 2018/8/9.
 */

public abstract class LoadMoreAdapter extends RecyclerView.Adapter<CommonRcViewHolder>{
    protected int ITEM_TYPE_LOAD = 2;
    protected String loadMoreText = "加载更多";
    protected  boolean isLoadMore;
    @Override
    public int getItemViewType(int position) {
        if(!isLoadMore){
            return 1;
        }
        if (position == getItemCount() - 1){
            return ITEM_TYPE_LOAD;
        }else {
            return 1;
        }
    }

    @Override
    public CommonRcViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_LOAD){
            View view = LayoutInflater.from(parent.getContext()).inflate(getFooterViewResId(),parent,false);
            return new CommonRcViewHolder(view);
        }else {
            return getViewHolder(parent,viewType);
        }
    }

    @Override
    public void onBindViewHolder(CommonRcViewHolder holder, int position) {
        if (getItemViewType(position) == ITEM_TYPE_LOAD){
            TextView tv = holder.getView(getFooterTextViewResId());
            tv.setText(loadMoreText);
        }else {
            loadData(holder, position);

        }
    }

    @Override
    public int getItemCount() {

        return getCount() + (isLoadMore ? 1 : 0);
    }

    public void setLoadMoreText(String loadMoreText) {
        this.loadMoreText = loadMoreText;
        notifyItemChanged(getItemCount()-1);
    }

    //获取加载更多布局
    public int getFooterViewResId() {
        return R.layout.item_footer;
    }
    //获取加载更多id
    public int getFooterTextViewResId() {
        return R.id.tv_footer;
    }

    public abstract int getCount();
    public abstract CommonRcViewHolder getViewHolder(ViewGroup parent, int viewType);
    public abstract void loadData(CommonRcViewHolder holder, int position);
    public abstract void loadMore();

    /**
     * 开关加载更多
     * @param isLoad
     */
    public void setCanLoadMore(boolean isLoad){
        isLoadMore = isLoad;
    }

    public boolean getIsCanLoadMore(){
        return isLoadMore;
    }
}
